package com.example.ramcache.schema;

import com.example.ramcache.IEntity;
import com.example.ramcache.ServiceManager;
import com.example.ramcache.orm.Accessor;
import com.example.ramcache.orm.Querier;
import com.example.ramcache.persist.PersisterConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.Set;

/**
 * 缓存服务管理器工厂
 * @author frank
 */
@SuppressWarnings("rawtypes")
public class ServiceManagerFactory implements FactoryBean<ServiceManager> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private Accessor accessor;
    private Querier querier;
    private Set<Class<? extends IEntity<?>>> entityClasses;
    private Map<String, PersisterConfig> persisterConfig;
    private Map<String, Integer> constants;

    private ServiceManager cacheServiceManager;

    private long shutdownDelay;
    @Override
    public ServiceManager getObject() throws Exception {
        cacheServiceManager = new ServiceManager(entityClasses, accessor, querier, constants, persisterConfig);
        return cacheServiceManager;
    }

    @PreDestroy
    public void shutdown() {
        if (cacheServiceManager == null) {
            return;
        }

        logger.info("开始回写缓存数据...");
        cacheServiceManager.shutdown();
        try {
            Thread.sleep(shutdownDelay);
        } catch (InterruptedException e) {
        }
        logger.info("回写缓存数据完成...");
    }

    // Setter Methods ...

    public void setAccessor(Accessor accessor) {
        this.accessor = accessor;
    }


    public void setQuerier(Querier querier) {
        this.querier = querier;
    }

    public void setEntityClasses(Set<Class<? extends IEntity<?>>> entityClasses) {
        this.entityClasses = entityClasses;
    }

    public void setPersisterConfig(Map<String, PersisterConfig> persisterConfig) {
        this.persisterConfig = persisterConfig;
    }

    public void setConstants(Map<String, Integer> constants) {
        this.constants = constants;
    }

    // Other Methods

    @Override
    public Class<?> getObjectType() {
        return ServiceManager.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setShutdownDelay(long shutdownDelay) {
        this.shutdownDelay = shutdownDelay;
    }

}
